#include <iostream>
#include <limits>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

#include "handler.h"

using namespace std;

char *main_menu[] = {
	"				1:setting",
	"				2:default setting",
	"				3:SNMP",
	"				4:watch",
	"				5:information",
	NULL
};

/**
 * 旧的ip处理方法，不用
 */
/*
char *ip_menu[] = {
	"				1:DHCP or static",
	"				2:IP address",
	"				3:Gateway",
	"				4:Netmask",
	"				5:MAC address",
	"				6:back to the main menu",
	NULL
};
*/

void display_menu(char *menu[]);

/************************************************************************/
/*
ע��ȡ�������ź�����Ĭ����Ӧ
SIGINT�����̵��ж��źţ�ctrl+C
SIGQUIT�����̵��˳��ź� ctrl+��\��
SIGTSTP: ��̹����ź� ctrl+z����Ϊshell��������ź����б����õ���
*/
void sig_handler(int sig) 
{
//	cout << "				Caught signal" << endl;
	cout << endl;
	cout << "				>>>";
	cout.flush();
//	return;
}

void register_signal()
{
	if(signal(SIGINT,sig_handler) == SIG_ERR) cout << "				register SIGINT error" << endl;
	if(signal(SIGQUIT,sig_handler) == SIG_ERR)
		cout << "				register SIGINT error" << endl;
	if(signal(SIGTSTP,sig_handler) == SIG_ERR)
		cout << "				register SIGINT error" << endl;
}
/************************************************************************/

int main()
{
	/**
	 * debug时不会捕获SIGINT，SIGQUIT和SIGTSTP信号
	 * */
#ifndef _debug_
	register_signal();
#endif
	initial_settings();
	int choice;
	
	while(1) {
		cout << "				choose commands:" << endl;
		display_menu(main_menu);
		cout << "				>>>";
//		cin.clear();
//		cin.ignore(numeric_limits <streamsize>::max(),'\n');
#if 0
		while(cin.peek() == '\n') {
			cin.ignore(numeric_limits <streamsize>::max(),'\n');;
			cout << "				>>>";
		}
		cin >> choice;
		if(cin.fail()) {
			cin.clear();
					cin.ignore(numeric_limits <streamsize>::max(),'\n');;
			cout << "				Input error, please input a number!" << endl << endl << endl;
		}
#endif
		
		choice = input_number(cin);
		switch(choice) {
			case 1:
				handle_info();
				cout << endl;
				handle_ipconfig();
				break;
			case 2:
				handle_default();
				break;
			case 3:
				handle_SNMP();
				break;
			case 4:
				if(handle_watch() < 0)
					cout << "				Sorry, can't display the latest logs!" << endl;
				break;
			case 5:
				handle_info();
				handle_gpsinput();
				cout << endl;
				break;
			default:
				cout << "				Sorry, you choice is not supported! " <<endl;
				cout << "				Please choose again:" << endl << endl << endl;
		}
	}
	return 0;
}

/************************************************************************/
/* 
��ʾ�˵�
*/
/************************************************************************/
void display_menu(char *menu[])
{
	char **p = menu;
	while(*p)
		cout << *p++ << endl;
}
